﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChurchData.Business;
using System.Collections;
using System.IO;

namespace ChurchData
{
    public partial class PeopleBasicUC : UserControl
    {
        #region Fields / Properties
        private int PeoplePK { get; set; }
        private People Person { get; set; }
        public string FirstName { get { return txtFirstName.Text; } }
        public string LastName { get { return txtLastName.Text; } }
        public bool HasUnsavedChanges { get; set; }
        #endregion Fields / Properties

        #region Constructor
        public PeopleBasicUC()
        {
            InitializeComponent();
        }

        #endregion Constructor

        #region Populate Methods
        private void PopulateGenderCombo()
        {
            cboGender.Items.Add("");
            cboGender.Items.Add("Male");
            cboGender.Items.Add("Female");
        }

        private void PopulateMaritalStatusCombo(int? selectedFK)
        {
            List<GenericLKTableResults> drsMaritalStatus = new LKMaritalStatusBO().GetActiveRecords(selectedFK);
            this.cboMaritalStatus.DataSource = drsMaritalStatus;
            this.cboMaritalStatus.DisplayMember = "Description";
            this.cboMaritalStatus.ValueMember = "Pk";

            if (selectedFK != null)
                this.cboMaritalStatus.SelectedValue = selectedFK;
            else
                this.cboMaritalStatus.SelectedValue = -1;
        }

        private void PopulateAssociationCombo(int? selectedFK)
        {
            List<GenericLKTableResults> drsAssociation = new LKAssociationBO().GetActiveRecords(selectedFK);
            this.cboAssociation.DataSource = drsAssociation;
            this.cboAssociation.DisplayMember = "Description";
            this.cboAssociation.ValueMember = "Pk";

            if (selectedFK != null)
                this.cboAssociation.SelectedValue = selectedFK;
            else
                this.cboAssociation.SelectedValue = -1;
        }

        public void LoadPersonInfo(int peoplePK)
        {
            this.PeoplePK = peoplePK;
            PeopleBO pBO = new PeopleBO();
            this.Person = pBO.GetRecordByPK(peoplePK);
            txtFirstName.Text = Person.FirstName;
            txtLastName.Text = Person.LastName;
            txtSuffix.Text = Person.Suffix;
            txtNickname.Text = Person.Nickname;
            txtTitle.Text = Person.Title;

            this.PopulateGenderCombo();
            if (Person.Gender == null)
                cboGender.SelectedIndex = 0;
            else if (Person.Gender == Convert.ToChar("M"))
                cboGender.SelectedIndex = 1;
            else if (Person.Gender == Convert.ToChar("F"))
                cboGender.SelectedIndex = 2;

            if (Person.Birthdate == null)
            {
                dtpBirthdate.Checked = false;
            }
            else
            {
                dtpBirthdate.Checked = true;
                dtpBirthdate.Value = Convert.ToDateTime(Person.Birthdate);
            }

            this.PopulateMaritalStatusCombo(Person.LKMaritalStatusFK);
            this.PopulateAssociationCombo(Person.LKAssociationFK);

            this.txtNotes.Text = Person.Notes;
            this.txtSpecialNeeds.Text = Person.SpecialNeeds;

            if (Person.Picture != null)
            {
                MemoryStream ms = new MemoryStream(Person.Picture.ToArray());
                picPortrait.BackgroundImage = Bitmap.FromStream(ms);
            }

            if (UserInformation.ViewOnlyInd) this.SetReadOnly();
            HasUnsavedChanges = false;
            this.SetChangeEvents();
        }

        private void SetChangeEvents()
        {
            txtFirstName.TextChanged += new EventHandler(controlChanged);
            txtLastName.TextChanged += new EventHandler(controlChanged);
            txtSuffix.TextChanged += new EventHandler(controlChanged);
            txtNickname.TextChanged += new EventHandler(controlChanged);
            txtTitle.TextChanged += new EventHandler(controlChanged);
            txtNotes.TextChanged += new EventHandler(controlChanged);
            txtSpecialNeeds.TextChanged += new EventHandler(controlChanged);
            cboGender.SelectedIndexChanged += new EventHandler(controlChanged);
            cboMaritalStatus.SelectedIndexChanged += new EventHandler(controlChanged);
            cboMaritalStatus.SelectedIndexChanged += new EventHandler(controlChanged);
            dtpBirthdate.ValueChanged += new EventHandler(controlChanged);
        }

        private void SetReadOnly()
        {
            this.btnImage.Enabled = false;
            this.txtFirstName.ReadOnly = true;
            this.txtLastName.ReadOnly = true;
            this.txtSuffix.ReadOnly = true;
            this.txtNickname.ReadOnly = true;
            this.txtTitle.ReadOnly = true;
            this.dtpBirthdate.Enabled = false;
            this.cboGender.Enabled = false;
            this.cboMaritalStatus.Enabled = false;
            this.cboAssociation.Enabled = false;
            this.txtNotes.ReadOnly = true;
            this.txtSpecialNeeds.ReadOnly = true;
            
            this.txtFirstName.BackColor = Color.White;
            this.txtLastName.BackColor = Color.White;
            this.txtSuffix.BackColor = Color.White;
            this.txtNickname.BackColor = Color.White;
            this.txtTitle.BackColor = Color.White;
            this.txtNotes.BackColor = Color.White;
            this.txtSpecialNeeds.BackColor = Color.White;
        }
        #endregion Populate Methods

        #region Control Events
        private void btnImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            DialogResult dlgResult = dlg.ShowDialog();
           
            if (dlg.CheckFileExists && dlgResult != DialogResult.Cancel)
            {
                try
                {
                    FileStream st = File.Open(dlg.FileName, FileMode.Open);
                    Image img = Image.FromStream(st);
                    st.Close();

                    // There's a limit to how big of a file is really necessary.
                    if (img.Height > 1000 || img.Width > 1000)
                    {
                        // This is to "Prevent using images internal thumbnail"
                        img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        img.RotateFlip(RotateFlipType.Rotate180FlipNone);

                        int newWidth = 1000;
                        int newHeight = img.Height * newWidth / img.Width;
                        if (newHeight > 1000)
                        {
                            // Resize with height instead of width
                            newWidth = img.Width * 1000 / img.Height;
                            newHeight = 1000;
                        }

                        Image newImage = img.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
                        picPortrait.BackgroundImage = newImage;
                    }
                    else
                        picPortrait.BackgroundImage = img;

                    HasUnsavedChanges = true;
                }
                catch (Exception exc)
                {
                    if (exc.Message.IndexOf("Parameter is not valid") > -1)
                    {
                        MessageBox.Show("Terribly sorry but an error occurred assigning that image.  The error suggests that the file is either an incompatible image type or not an image at all?");
                    }
                    else
                    {
                        MessageBox.Show("Terribly sorry but an error occurred assigning that image.  If the image is in a compressed or network folder please copy it to a local folder and try again.\n\nActual Error Message:\n" + exc.Message);
                    }
                }
            }
        }

        private void btnRemoveImage_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("Are you sure?", "Confirm image removal", MessageBoxButtons.YesNo))
            {
                picPortrait.BackgroundImage = null;
                HasUnsavedChanges = true;
            }
        }

        private void controlChanged(object sender, EventArgs e)
        {
            this.HasUnsavedChanges = true;
        }

        #endregion Control Events

        #region Save Methods
        public void SaveIt()
        {
            if (!ValidateEntries()) return;

            string gender = cboGender.Text.Trim();
            if (gender == null || gender == "") gender = " ";
            if (gender.Length > 1) gender = gender.Substring(0, 1);
            DateTime? birthDate = dtpBirthdate.Value;
            if (!dtpBirthdate.Checked) birthDate = null;
            int? maritalStatusFK = null;
            if (cboMaritalStatus.SelectedValue != null) maritalStatusFK = (int)cboMaritalStatus.SelectedValue;
            int? associationFK = null;
            if (cboAssociation.SelectedValue != null) associationFK = (int)cboAssociation.SelectedValue;
            System.Data.Linq.Binary img = null;
            if (picPortrait.BackgroundImage != null)
            {
                MemoryStream ms = new MemoryStream();
                picPortrait.BackgroundImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = new System.Data.Linq.Binary(ms.ToArray());
            }
            
            PeopleBO pBO = new PeopleBO();
            pBO.UpdateBasic(PeoplePK, txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtSuffix.Text.Trim(), txtNickname.Text.Trim(),
                txtTitle.Text.Trim(), gender, birthDate, maritalStatusFK, associationFK, txtNotes.Text.Trim(), txtSpecialNeeds.Text.Trim(), img);
            
            this.HasUnsavedChanges = false;
        }

        private bool ValidateEntries()
        {
            if (txtFirstName.Text.Trim().Length == 0 || txtLastName.Text.Trim().Length == 0)
            {
                MessageBox.Show("First and Last Names are Required!", "Cannot Save!");
                return false;
            }
            return true;
        }
        #endregion Save Methods
    }
}
